package com.partners.service.Impl;

import com.partners.configure.wechatmp.WxMpConfiguration;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.dto.NewsInputDTO;
import com.partners.dao.dto.TemplateDTO;
import com.partners.dao.basic.WxTemplateDao;
import com.partners.dao.bo.WxTemplateDO;
import com.partners.model.BusinessException;
import com.partners.service.TemplateService;
import com.partners.utils.TimestampUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author liangyongle
 * @date 2019-01-10
 */
@Service
@Slf4j
public class TemplateServcieImpl implements TemplateService {

    @Resource
    private WxMpProperties wxMpProperties;

    public final static String templateId = "WbOhTRrGM7K_rjteFrnOZCp9toddGhyxxtCduyBTx4I";


    @Resource
    private WxTemplateDao wxTemplateDao;

    /**发送模板消息
     * @param   templateDTO  TemplateDTO
     *          openId  String
     * */
    @Override
    public void sendHanleTemplate(TemplateDTO templateDTO, String openId) {

        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
        //实例化模板对象
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(templateId);
        //设置发送给哪个用户
        wxMpTemplateMessage.setToUser(openId);
        //构建消息格式
        List<WxMpTemplateData> list= Arrays.asList(
            new WxMpTemplateData("first",templateDTO.getFirst()),
            new WxMpTemplateData("keyword1",templateDTO.getKeyword1()),
            new WxMpTemplateData("keyword2",templateDTO.getKeyword2()),
            new WxMpTemplateData("remark",templateDTO.getRemark())
        );
        //放进模板对象。准备发送
        wxMpTemplateMessage.setData(list);
        wxMpTemplateMessage.setUrl(templateDTO.getUrl());
        try {
            //发送模板
            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
        } catch (WxErrorException e) {
            e.printStackTrace();
            throw BusinessException.of(ErrorMessageEnum.TEMPLATE_SEND_ERROR);
        }


    }

    /**
    * 定时发送任务
    * */

    @Override
    public void sendTemplateTask() {
        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
        //设置模板ID
        wxMpTemplateMessage.setTemplateId(templateId);
          //拉取10条需要发送的消息
         List<WxTemplateDO> wxTemplateDO= wxTemplateDao.selectTemplate(10);
        //构建消息格式
         if(wxTemplateDO != null){
             //设置发送给哪个用户
             for (WxTemplateDO map:wxTemplateDO){
                 wxMpTemplateMessage.setToUser(map.getSendto());
                 wxMpTemplateMessage.setUrl(map.getUrl());
                 List<WxMpTemplateData> list= Arrays.asList(
                     new WxMpTemplateData("first",map.getFirst()),
                     new WxMpTemplateData("keyword1",map.getKeyword1()),
                     new WxMpTemplateData("keyword2",map.getKeyword2()),
                     new WxMpTemplateData("remark",map.getRemarks())
                 );
               // 放进模板对象。准备发送
                wxMpTemplateMessage.setData(list);
                try {
                    //发送模板
                    wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
                    //成功回写地址
                    WxTemplateDO template = new WxTemplateDO();
                    template.setId(map.getId());
                    template.setSendtime(TimestampUtils.timestamp());
                    Byte status = 1;
                    template.setStatus(status);
                    wxTemplateDao.updateByPrimaryKeySelective(template);
                } catch (WxErrorException e) {
                    log.info("错误信息:{}",e.getError().getErrorMsg());
                    //e.printStackTrace();

                    //throw BusinessException.of(ErrorMessageEnum.TEMPLATE_SEND_ERROR);
                }
             }

         }




//        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(appId);
//        //实例化模板对象
//        WxMpTemplateMessage wxMpTemplateMessage = new WxMpTemplateMessage();
//        //设置模板ID
//        wxMpTemplateMessage.setTemplateId(templateId);
//        //设置发送给哪个用户
//        wxMpTemplateMessage.setToUser(openId);
//        //构建消息格式
//        List<WxMpTemplateData> list= Arrays.asList(
//            new WxMpTemplateData("first",templateDTO.getFirst()),
//            new WxMpTemplateData("keyword1",templateDTO.getKeyword1()),
//            new WxMpTemplateData("keyword2",templateDTO.getKeyword2()),
//            new WxMpTemplateData("remark",templateDTO.getRemark())
//        );
//        //放进模板对象。准备发送
//        wxMpTemplateMessage.setData(list);
//        try {
//            //发送模板
//            wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
//        } catch (WxErrorException e) {
//            e.printStackTrace();
//            throw BusinessException.of(ErrorMessageEnum.TEMPLATE_SEND_ERROR);
//        }


    }

    /**
     * 发送图文消息
     * @retrun
     * */

    @Override
    public void sendNewsMessage(NewsInputDTO newsInputDTO, String openId) {
        final WxMpService wxMpService = WxMpConfiguration.getMpServices().get(wxMpProperties.getBaseAppId());
        WxMpKefuMessage.WxArticle article1 = new  WxMpKefuMessage.WxArticle();
        article1.setUrl(newsInputDTO.getUrl());
        article1.setPicUrl(newsInputDTO.getPicUrl());
        article1.setDescription(newsInputDTO.getDescription());
        article1.setTitle(newsInputDTO.getTitle());
        List<WxMpKefuMessage.WxArticle> articles;
        articles =new ArrayList<>(1);
        articles.add(article1);

        WxMpKefuMessage message = new WxMpKefuMessage();
        message.setMsgType(WxConsts.KefuMsgType.NEWS);
        message.setToUser(openId);
        message.setArticles(articles);
        try {
            wxMpService.getKefuService().sendKefuMessage(message);
        } catch (WxErrorException e) {
            //e.printStackTrace();
            throw BusinessException.of(ErrorMessageEnum.NEWS_SEND_ERROR);
        }
    }


}
